package com.ruoyi.project.meal.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.ruoyi.common.excel.ExcelFillCellMergeStrategy;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.FileUtil;
import com.ruoyi.common.utils.meal.MealDataUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.poi.MyHandler;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.meal.domain.MealMilk;
import com.ruoyi.project.meal.domain.MealServiceObjects;
import com.ruoyi.project.meal.domain.MealServiceObjectsList;
import com.ruoyi.project.meal.domain.MealWorker;
import com.ruoyi.project.meal.service.IMealServiceObjectsListService;
import com.ruoyi.project.meal.service.IMealServiceObjectsService;
import com.ruoyi.project.meal.utils.DataParse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 服务对象报餐记录Controller
 * 
 * @author ywy
 * @date 2024-03-05
 */
@Controller
@RequestMapping("/meal/meal")
public class MealServiceObjectsController extends BaseController
{
    private String prefix = "meal/meal";

    @Autowired
    private IMealServiceObjectsService mealServiceObjectsService;
    @Autowired
    private IMealServiceObjectsListService mealServiceObjectsListService;

    @GetMapping()
    public String meal()
    {
        return prefix + "/meal";
    }

    /**
     * 查询服务对象报餐记录列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(MealServiceObjects mealServiceObjects)
    {
        startPage();
        List<MealServiceObjects> list = mealServiceObjectsService.selectMealServiceObjectsList(mealServiceObjects);
        return getDataTable(list);
    }

    @GetMapping("/detail/{reportDate}/{className}/{campus}")
    public String detail(@PathVariable("reportDate") String reportDate  ,@PathVariable("className") String className  ,@PathVariable("campus") String campus ,ModelMap mmap)
    {
        mmap.put("reportDate", reportDate);
        mmap.put("className", className);
        mmap.put("campus", campus);
        return prefix + "/meal";
    }

    @GetMapping("/dataParse")
    public String listXXX(MealServiceObjects mealServiceObjects)
    {
        MealServiceObjectsList m=new MealServiceObjectsList();
        List<MealServiceObjectsList> mList= mealServiceObjectsListService.selectCount(m);
        if(mList !=null && mList.size()>0){
            for (MealServiceObjectsList mSer:mList ) {
                List<MealServiceObjectsList> detalList=mealServiceObjectsListService.selectMealServiceObjectsListList(mSer);
                List<MealServiceObjects> sList= DataParse. parseObjects(detalList);
                for (MealServiceObjects  so:sList   ) {
                    mealServiceObjectsService.insertMealServiceObjects(so);
                }
            }
        }
        return prefix + "/meal";
    }

    /**
     * 导出服务对象报餐记录列表
     */
    @Log(title = "服务对象报餐记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(MealServiceObjects mealServiceObjects)
    {
        List<MealServiceObjects> list = mealServiceObjectsService.selectMealServiceObjectsList(mealServiceObjects);
        ExcelUtil<MealServiceObjects> util = new ExcelUtil<MealServiceObjects>(MealServiceObjects.class);
        return util.exportExcel(list, "服务对象报餐记录数据");
    }

    /**
     * 新增服务对象报餐记录
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存服务对象报餐记录
     */
    @Log(title = "服务对象报餐记录", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(MealServiceObjects mealServiceObjects)
    {
        return toAjax(mealServiceObjectsService.insertMealServiceObjects(mealServiceObjects));
    }

    /**
     * 修改服务对象报餐记录
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap)
    {

        MealServiceObjects mealServiceObjects = mealServiceObjectsService.selectMealServiceObjectsById(id);
        mmap.put("mealServiceObjects", mealServiceObjects);
        return prefix + "/edit";
    }

    /**
     * 修改保存服务对象报餐记录
     */
    @Log(title = "服务对象报餐记录", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(MealServiceObjects mealServiceObjects)
    {
        return toAjax(mealServiceObjectsService.updateMealServiceObjects(mealServiceObjects));
    }

    /**
     * 删除服务对象报餐记录
     */
    @Log(title = "服务对象报餐记录", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(mealServiceObjectsService.deleteMealServiceObjectsByIds(ids));
    }

    /**
     * 查询报餐明细
     */
    @GetMapping("/detail/{mealId}")
    public String detail(@PathVariable("mealId") Integer mealId, ModelMap mmap)
    {
        mmap.put("mealId",mealId);
        return "meal/meallist/mealList";
    }

    @GetMapping("/reportShow")
    public String reportShow()
    {
        return prefix + "/mealReportList";
    }

    @PostMapping("/reportList")
    @ResponseBody
    public TableDataInfo reportList(MealServiceObjects mealServiceObjects)
    {
        startPage();
        List<MealServiceObjects> list = mealServiceObjectsService.selectReportList(mealServiceObjects);
        return getDataTable(list);
    }

    @GetMapping("/listCountShow")
    public String listCountShow()
    {
        return prefix + "/mealCount";
    }

    @GetMapping("/detailMeal")
    public String detailMeal( String reportDate ,String className  , String campus,ModelMap mmap)
    {
        mmap.put("reportDate", reportDate);
        mmap.put("className", className);
        mmap.put("campus", campus);
        return prefix + "/mealCount";
    }

    @PostMapping("/listCount")
    @ResponseBody
    public TableDataInfo listCount(MealServiceObjects mealServiceObjects)
    {
        startPage();
        List<MealServiceObjects> list = mealServiceObjectsService.selectCount(mealServiceObjects);
        return getDataTable(list);
    }

    /**
     * 报表导出
     */
    @Log(title = "职工报餐", businessType = BusinessType.EXPORT)
    @PostMapping("/exportReport")
    @ResponseBody
    public AjaxResult exportReport(MealServiceObjects mealServiceObjects)
    {
        String reportDate=String.valueOf(mealServiceObjects.getParams().get("startTime"))+String.valueOf(mealServiceObjects.getParams().get("endTime"));
        List<MealServiceObjects> list = mealServiceObjectsService.selectReportList(mealServiceObjects);

        ExcelUtil<MealMilk> util = new ExcelUtil<MealMilk>(MealMilk.class);
        String templateFileName = FileUtil.getPath() + "excel" + File.separator + "mealService.xlsx";
        String fileName=System.currentTimeMillis() + ".xlsx";
        String fileNamePath= util.getAbsoluteFile(fileName );
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 方案1
        try (ExcelWriter excelWriter = EasyExcel.write(fileNamePath).withTemplate(templateFileName).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet().registerWriteHandler(new MyHandler()).build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(list, fillConfig, writeSheet);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("reportDate", reportDate);
//            map.put("campus", mealServiceObjects.getCampus());
            excelWriter.fill(map, writeSheet);
        }
        return AjaxResult.success(fileName);
    }

    /**
     *
     */
    @PostMapping("/exportDayReport")
    @ResponseBody
    public AjaxResult exportDayReport(MealServiceObjects mealServiceObjects , HttpServletResponse response) throws IOException {
        startPage(0,100000);
        List<MealServiceObjects> list = mealServiceObjectsService.selectCount(mealServiceObjects);
        ExcelUtil<MealServiceObjects> util = new ExcelUtil<MealServiceObjects>(MealServiceObjects.class);
        String templateFileName = FileUtil.getPath() + "excel" + File.separator + "mealServiceDayReport.xlsx";
        String fileName=System.currentTimeMillis() + ".xlsx";
        String fileNamePath= util.getAbsoluteFile(fileName );
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //合并的列学号
        int[] mergeColumnIndex=new int[]{};
        // 方案1
        try (ExcelWriter excelWriter = EasyExcel.write(fileNamePath).withTemplate(templateFileName).registerWriteHandler(new ExcelFillCellMergeStrategy(4,mergeColumnIndex)).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(list, fillConfig, writeSheet);
            Map<String, Object> map = new HashMap<String, Object>();
            excelWriter.fill(map, writeSheet);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(fileName);
    }

    /**
     * 导出牛奶日明细报表
     */
    @PostMapping("/exportDayDetailReport")
    @ResponseBody
    public AjaxResult exportDayDetailReport(MealServiceObjects mealServiceObjects , HttpServletResponse response) throws IOException {
        startPage(0,100000);
        List<MealServiceObjects> list = mealServiceObjectsService.selectMealServiceObjectsList(mealServiceObjects);
        ExcelUtil<MealMilk> util = new ExcelUtil<MealMilk>(MealMilk.class);
        String templateFileName = FileUtil.getPath() + "excel" + File.separator + "mealServiceDayReportDetail.xlsx";
        String fileName=System.currentTimeMillis() + ".xlsx";
        String fileNamePath= util.getAbsoluteFile(fileName );
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //合并的列学号
        int[] mergeColumnIndex=new int[]{0,1,2,19};
        // 方案1
        try (ExcelWriter excelWriter = EasyExcel.write(fileNamePath).withTemplate(templateFileName).registerWriteHandler(new ExcelFillCellMergeStrategy(4,mergeColumnIndex)).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(list, fillConfig, writeSheet);
            Map<String, Object> map = new HashMap<String, Object>();
            excelWriter.fill(map, writeSheet);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(fileName);
    }



}
